package com.coocaa.app.lib.cleaner.deleter.apk.impl;

import android.content.Context;
import android.text.TextUtils;

import com.coocaa.app.lib.cleaner.deleter.apk.ApkDeleterFactory;
import com.coocaa.app.lib.cleaner.deleter.utils.FileUtils;
import com.coocaa.app.lib.cleaner.mgr.DataHolder;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lu on 17-4-13.
 */

public class ApkDeleterImpl implements ApkDeleterFactory.ApkDeleter {
    @Override
    public void delete(Context context, final List<String> apks, final ApkDeleterListener listener) {
        DeleterThread.post(new Runnable() {
            @Override
            public void run() {
                listener.onApkDeleterStart(true, apks);
                if (apks != null && apks.size() > 0) {
                    List<String> list = new ArrayList<String>();
                    long cleanSize = 0;
                    for (String path : apks) {
                        try {
                            long tempsize = new File(path).length();
                            FileUtils.deleteFile(path);
                            cleanSize += tempsize;
                            list.add(path);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (holder != null)
                            holder.removeAPK(path);
                    }
                    if (cleanSize > 0) {
                        listener.onApkDeleterEnd(true, list, true, cleanSize);
                        return;
                    }
                }
                listener.onApkDeleterEnd(true, apks, false, 0);
            }
        });
    }

    @Override
    public void delete(Context context, final String apk, final ApkDeleterListener listener) {
        DeleterThread.post(new Runnable() {
            @Override
            public void run() {
                List<String> list = new ArrayList<String>();
                list.add(apk);
                listener.onApkDeleterStart(false, list);
                if (!TextUtils.isEmpty(apk)) {
                    long cleanSize = 0;
                    try {
                        long tempsize = new File(apk).length();
                        FileUtils.deleteFile(apk);
                        cleanSize += tempsize;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (holder != null)
                        holder.removeAPK(apk);
                    if (cleanSize > 0) {
                        listener.onApkDeleterEnd(false, list, true, cleanSize);
                        return;
                    }
                }
                listener.onApkDeleterEnd(false, list, false, 0);
            }
        });
    }

    private DataHolder holder;

    @Override
    public void init(DataHolder holder) {
        this.holder = holder;
    }
}
